﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using BGShell.Components;
using BGShell.PowerShell.Runspaces;

namespace BGShell.PowerShell.LanguageService
{
    partial class PSLanguageService
    {
        private sealed class DataTipCache
        {
            private readonly Object _syncRoot = new Object();
            private readonly Dictionary<String, DataTipItem>[] _caches = new Dictionary<String, DataTipItem>[3];

            public void Add(DataTipInfo info)
            {
                Debug.Assert(info.Type != DataTipType.None);
                Debug.Assert(info.Item != null);

                lock (_syncRoot)
                {
                    GetCache(info.Type)[info.Text] = info.Item;
                }
            }

            public DataTipItem this[DataTipInfo info]
            {
                get
                {
                    lock (_syncRoot)
                    {
                        var cache = GetCache(info.Type);
                        DataTipItem result;

                        if (cache.TryGetValue(info.Text, out result))
                        {
                            return result;
                        }
                    }

                    return null;
                }
            }

            private Dictionary<String, DataTipItem> GetCache(DataTipType tokenType)
            {
                switch (tokenType)
                {
                    case DataTipType.Command:
                        return GetCache(0);

                    case DataTipType.Variable:
                        return GetCache(1);

                    case DataTipType.Type:
                        return GetCache(2);
                }

                throw new ArgumentException(null, "tokenType");
            }

            private Dictionary<String, DataTipItem> GetCache(Int32 index)
            {
                if (_caches[index] == null)
                {
                    _caches[index] = new Dictionary<String, DataTipItem>(StringComparer.OrdinalIgnoreCase);
                }

                return _caches[index];
            }
        }
    }
}